const db = uniCloud.database()
module.exports = {
	removeById: async ({
		collection,
		id,
		transaction
	}) => {
		let db2 = transaction || db;
		try {
			await db2.collection(collection).doc(id).remove()
		} catch (e) {
			throw e;
		}
	},
	getById: async ({
		collection,
		id,
		field,
		transaction
	}) => {
		let db2 = transaction || db;
		try {
			var doc = db2.collection(collection).doc(id)
			if (field) {
				doc = doc.field(field)
			}
			let res = await doc.get();
			if (Array.isArray(res.data)) {
				return res.data[0];
			} else {
				return res.data
			}
		} catch (e) {
			throw e;
		}
	},
	getOne: async ({
		collection,
		where,
		field
	}) => {
		try {
			var coll = db.collection(collection).where(where)
			if (field) {
				coll = coll.field(field)
			}
			let res = await coll.get();
			if (res.data.length) {
				return res.data[0];
			}
		} catch (e) {
			throw e;
		}
	},
	getList: async ({
		collection,
		where,
		field,
		orderByList
	}) => {
		try {
			var coll = db.collection(collection)
			if (where) {
				coll = coll.where(where)
			}
			if (field) {
				coll = coll.field(field)
			}
			if (orderByList && orderByList.length) {
				orderByList.forEach(item => {
					coll = coll.orderBy(item[0], item[1])
				})
			}
			let res = await coll.get();
			return res.data;
		} catch (e) {
			throw e;
		}
	},
	getPage: async ({
		collection,
		pageNum = 1,
		pageSize = 10,
		where,
		field,
		orderByList
	}) => {
		try {
			var coll = db.collection(collection)
			if (where) {
				coll = coll.where(where)
			}
			let countRes = await coll.count();
			let page = {
				total: countRes.total,
				list: []
			}
			if (countRes.total) {
				if (field) {
					coll = coll.field(field)
				}
				if (orderByList && orderByList.length) {
					orderByList.forEach(item => {
						coll = coll.orderBy(item[0], item[1])
					})
				}
				coll = coll.skip((pageNum - 1) * pageSize).limit(pageSize)
				let listRes = await coll.get();
				page.list = listRes.data
			}
			return page;
		} catch (e) {
			throw e;
		}
	},
	getCount: async ({
		collection,
		where
	}) => {
		try {
			var coll = db.collection(collection)
			if (where) {
				coll = coll.where(where)
			}
			let res = await coll.count();
			return res.total;
		} catch (e) {
			throw e;
		}
	},
	insert: async ({
		collection,
		data,
		transaction
	}) => {
		let db2 = transaction || db;
		try {
			let res = await db2.collection(collection).add(data);
			data._id = res.id;
		} catch (e) {
			throw e;
		}
	},
	updateById: async ({
		collection,
		data,
		transaction
	}) => {
		let db2 = transaction || db;
		try {
			let t = Object.assign({}, data);
			delete t._id;
			await db2.collection(collection).doc(data._id).update(t);
		} catch (e) {
			throw e;
		}
	}
}
